package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.reids.subpub.eRedisChannelType;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.usercenter.newadmin.CenterReloadHelper;
import com.yanqu.road.web.mgr.AllActivityMainInfoMgr;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/usercenter/admin")
public class CenterActivityAdminController {

    /**
     *  8.1 活动过期
     */
    @ResponseBody
    @RequestMapping(value = "activityOverTime", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String activityOverTime(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("importBatch")){
            return AdminResult.failMsg("importBatch 为空").toJsonString();
        }

        long importBatch = jsonObject.getLongValue("importBatch");
        if(importBatch <= 0){
            return AdminResult.failMsg("importBatch 无效参数").toJsonString();
        }

        if(!jsonObject.containsKey("beginTime")){
            return AdminResult.failMsg("beginTime 为空").toJsonString();
        }

        if(!jsonObject.containsKey("endTime")){
            return AdminResult.failMsg("endTime 为空").toJsonString();
        }

        if(!jsonObject.containsKey("beginShowTime")){
            return AdminResult.failMsg("beginShowTime 为空").toJsonString();
        }

        if(!jsonObject.containsKey("endShowTime")){
            return AdminResult.failMsg("endShowTime 为空").toJsonString();
        }

        long beginTime = DateHelper.str2timestamp(jsonObject.getString("beginTime"));
        long endTime = DateHelper.str2timestamp(jsonObject.getString("endTime"));

        long beginShowTime = DateHelper.str2timestamp(jsonObject.getString("beginShowTime"));
        long endShowTime = DateHelper.str2timestamp(jsonObject.getString("endShowTime"));

        boolean result = new AdminCommonDaoImpl().updateActivityInfo(importBatch, beginTime, beginShowTime, endTime, endShowTime);

        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  8.2 获取活动子渠道配置（服务端提供）
     */
    @ResponseBody
    @RequestMapping(value = "getByImportBatch", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getByImportBatch(HttpServletRequest request, @RequestBody JSONObject jsonObject){


        return AdminResult.defaultInstance().toJsonString();
    }


    /**
     *  8.3 活动屏蔽
     */
    @ResponseBody
    @RequestMapping(value = "activityIgnore", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String activityIgnore(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("importBatch")){
            return AdminResult.failMsg("importBatch 为空").toJsonString();
        }

        long importBatch = jsonObject.getLongValue("importBatch");
        if(importBatch <= 0){
            return AdminResult.failMsg("importBatch 无效参数").toJsonString();
        }

        if(!jsonObject.containsKey("channelId")){
            return AdminResult.failMsg("channelId 为空").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");

        Set<Long> serverSet = new HashSet<>();
        List<Integer> batchActivityId = new AdminCommonDaoImpl().getBatchActivityId(importBatch, serverSet);
        if(batchActivityId.size() == 0){
            return AdminResult.failMsg("没有对应批次的活动").toJsonString();
        }

        List<Map<String, Object>> updateList = new ArrayList<>();
        for (Integer activityId : batchActivityId) {
            Map<String, Object> map = new HashMap<>();
            map.put("activityId", activityId);
            map.put("state", 0);
            updateList.add(map);
        }

        boolean result = new AdminCommonDaoImpl().batchUpdateActivityIgnore(updateList);
        if(!result) {
            return AdminResult.failMsg("失败").toJsonString();
        }

        //刷新区服接口
        List<ServerInfo> openServerList = ServerListMgr.getChannelServerList(channelId);
        openServerList.removeIf(serverInfo -> !serverSet.contains(serverInfo.getServerId()));
        String msg = CenterReloadHelper.serverMgrReload(openServerList, "ActivityIgnoreMgr", 20);
        //刷新区服接口
        AdminResult adminResult = AdminResult.defaultInstance();
        adminResult.setMsg(msg);
        return adminResult.toJsonString();
    }

    /**
     *  8.4 取消活动屏蔽
     */
    @ResponseBody
    @RequestMapping(value = "cancelActivityIgnore", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String cancelActivityIgnore(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("importBatch")){
            return AdminResult.failMsg("importBatch 为空").toJsonString();
        }

        long importBatch = jsonObject.getLongValue("importBatch");
        if(importBatch <= 0){
            return AdminResult.failMsg("importBatch 无效参数").toJsonString();
        }

        if(!jsonObject.containsKey("channelId")){
            return AdminResult.failMsg("channelId 为空").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");

        Set<Long> serverSet = new HashSet<>();
        List<Integer> batchActivityId = new AdminCommonDaoImpl().getBatchActivityId(importBatch, serverSet);
        if(batchActivityId.size() == 0){
            return AdminResult.failMsg("没有对应批次的活动").toJsonString();
        }

        List<Map<String, Object>> updateList = new ArrayList<>();
        for (Integer activityId : batchActivityId) {
            Map<String, Object> map = new HashMap<>();
            map.put("activityId", activityId);
            map.put("state", 1);
            updateList.add(map);
        }

        boolean result = new AdminCommonDaoImpl().batchUpdateActivityIgnore(updateList);
        if(!result) {
            return AdminResult.failMsg("失败").toJsonString();
        }

        //刷新区服接口
        List<ServerInfo> openServerList = ServerListMgr.getChannelServerList(channelId);
        openServerList.removeIf(serverInfo -> !serverSet.contains(serverInfo.getServerId()));
        String msg = CenterReloadHelper.serverMgrReload(openServerList, "ActivityIgnoreMgr", 20);
        //刷新区服接口
        AdminResult adminResult = AdminResult.defaultInstance();
        adminResult.setMsg(msg);
        return adminResult.toJsonString();
    }


    /**
     *  8.5 刷新活动配置
     */
    @ResponseBody
    @RequestMapping(value = "activityReload", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String activityReload(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("importIds")){
            return AdminResult.failMsg("importIds 为空").toJsonString();
        }

        List<Long> importBatchList = StringUtils.stringToLongList(jsonObject.getString("importIds"), ",");
        if(importBatchList.size() <= 0){
            return AdminResult.failMsg("importBatch 无效参数").toJsonString();
        }

        try {
            new ServerListMgr().init();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //区服信息
        Set<Long> serverSet = new HashSet<>();
        for (Long importBatch : importBatchList) {
            List<Integer> batchActivityId = new AdminCommonDaoImpl().getBatchActivityId(importBatch, serverSet);
            if(batchActivityId.size() == 0){
                return AdminResult.failMsg("没有对应批次的活动").toJsonString();
            }
        }

        String message = "AllActivityMainInfoMgr" + ";" + System.currentTimeMillis() / 1000;
        RedisManger.getRedisUtil().publish(eRedisChannelType.CenterManagerReload.getChannel(), eRedisChannelType.CenterManagerReload.getMessageKey(message));

        try{
            Thread.sleep(3000);
        }catch (Exception e){

        }

        List<ServerInfo> openServerList = ServerListMgr.getOpenServerList();
        openServerList.removeIf(serverInfo -> !serverSet.contains(serverInfo.getServerId()));
        String msg = CenterReloadHelper.serverMgrReload(openServerList, "ActivityMgr", 60);
        //刷新区服接口
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result.toJsonString();
    }

    /**
     *  8.6 根据活动类型刷新活动
     */
    @ResponseBody
    @RequestMapping(value = "activity/refreshType", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String activityrefreshType(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("type") || !jsonObject.containsKey("childType")){
            return AdminResult.failMsg("缺失参数").toJsonString();
        }

        int type = jsonObject.getIntValue("type");
        int childType = jsonObject.getIntValue("childType");

        try {
            new ServerListMgr().init();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //区服信息
        Set<Long> serverSet = new HashSet<>();
        List<Integer> batchActivityId = new AdminCommonDaoImpl().getBatchActivityId(type, childType, serverSet);
        if(batchActivityId.size() == 0){
            return AdminResult.failMsg("没有对应类型的活动").toJsonString();
        }

        //刷新区服接口
        List<ServerInfo> openServerList = ServerListMgr.getOpenServerList();
        openServerList.removeIf(serverInfo -> !serverSet.contains(serverInfo.getServerId()));
        String msg = CenterReloadHelper.serverMgrReload(openServerList, "ActivityMgr", 60);
        //刷新区服接口
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result.toJsonString();
    }

    /**
     * 51 后台导入配置表
     * 51.1 导入数据
     */
    @ResponseBody
    @RequestMapping(value = "backendImport", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String backendImport(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("channelId")){
            return AdminResult.failMsg("channelId 为空").toJsonString();
        }

        int channelId = jsonObject.getIntValue("channelId");

        if(!jsonObject.containsKey("activityList")){
            return AdminResult.failMsg("activityList 为空").toJsonString();
        }

        //先删除数据

        JSONArray activityList = jsonObject.getJSONArray("activityList");
        for (int i = 0; i < activityList.size(); i++) {
            JSONObject tableObject = activityList.getJSONObject(i);
            String tableName = tableObject.getString("tableName");
            JSONArray valueJsonArray = tableObject.getJSONArray("value");
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (int i1 = 0; i1 < valueJsonArray.size(); i1++) {
                Map<String, Object> dataMap = new HashMap<>();
                JSONArray jsonArray = valueJsonArray.getJSONArray(i1);
                for (int i2 = 0; i2 < jsonArray.size(); i2++) {
                    JSONObject object = jsonArray.getJSONObject(i2);
                    dataMap.put(object.getString("key"), object.get("value"));
                }
                dataList.add(dataMap);
            }
            if("t_s_goods_channel".equals(tableName)){
                new AdminCommonDaoImpl().batchDeleteChannelGoods(dataList, channelId);
                boolean b = new AdminCommonDaoImpl().batchUpdateChannelGoods(dataList, channelId);
                if(!b){
                    return AdminResult.failMsg("t_s_goods_channel 导入失败").toJsonString();
                }
            }else if("t_s_goods_bag_channel".equals(tableName)){
                new AdminCommonDaoImpl().batchDeleteChannelBagGoods(dataList, channelId);
                boolean b = new AdminCommonDaoImpl().batchUpdateChannelBagGoods(dataList, channelId);
                if(!b){
                    return AdminResult.failMsg("t_s_goods_bag_channel 导入失败").toJsonString();
                }
            }else if("t_s_language_channel".equals(tableName)){
                new AdminCommonDaoImpl().batchDeleteChannelLanguage(dataList, channelId);
                boolean b = new AdminCommonDaoImpl().batchUpdateChannelLanguage(dataList, channelId);
                if(!b){
                    return AdminResult.failMsg("t_s_language_channel 导入失败").toJsonString();
                }
            }else {
                return AdminResult.failMsg("表明无效").toJsonString();
            }

        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 51.2 刷新道具表
     */
    @ResponseBody
    @RequestMapping(value = "backendRefreshGoods", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String backendRefreshGoods(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("serverList")){
            return AdminResult.failMsg("serverList 为空").toJsonString();
        }
        JSONArray jsonArray = jsonObject.getJSONArray("serverList");
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            long id = jsonArray.getLongValue(i);
            list.add(id);
        }

        //刷新区服接口
        List<ServerInfo> serverList = new ArrayList<>();

        for (Long id : list) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(id);
            if(serverInfo != null){
                serverList.add(serverInfo);
            }
        }

        String msg = CenterReloadHelper.serverMgrReload(serverList, "CommonMgr", 30);
        //刷新区服接口
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result.toJsonString();
    }

    /**
     * 53.1 刷新语言表
     */
    @ResponseBody
    @RequestMapping(value = "backendRefreshLanguage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String backendRefreshLanguage(HttpServletRequest request, @RequestBody JSONObject jsonObject){
        if(!jsonObject.containsKey("serverList")){
            return AdminResult.failMsg("serverList 为空").toJsonString();
        }
        String serverStr = jsonObject.getString("serverList");
        List<Long> list = StringUtils.stringToLongList(serverStr, ",");

        //刷新区服接口
        List<ServerInfo> serverList = new ArrayList<>();

        for (Long id : list) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(id);
            if(serverInfo != null){
                serverList.add(serverInfo);
            }
        }

        String msg = CenterReloadHelper.serverMgrReload(serverList, "ServerLanguageMgr", 30);
        //刷新区服接口
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result.toJsonString();
    }


    /**
     *  28.空活动检测
     *  28.1 查询
     */
    @ResponseBody
    @RequestMapping(value = "activitySearch", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String activitySearch(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        int channelId = 0;
        if(jsonObject.containsKey("channelId")){
            channelId = jsonObject.getIntValue("channelId");
        }

        if(!jsonObject.containsKey("time")){
            return AdminResult.failMsg("time 为空").toJsonString();
        }

        String time = DateHelper.getCurrentDateTimeString();
        if(jsonObject.containsKey("time")){
            time = jsonObject.getString("time");
        }

        //所有活动
        Map<Integer, ActivityInfo> activityInfoMap = new AdminCommonDaoImpl().allInTimeActivity(time);

        List<Long> serverIdList = new ArrayList<>();
        JSONArray serverIds = jsonObject.getJSONArray("serverIds");
        for (int i = 0; i < serverIds.size(); i++) {
            serverIdList.add(serverIds.getLongValue(i));
        }

        //所有活动，需要的区服
        Map<Integer, List<Long>> activityServerMap = new HashMap<>();

        //0 全部  1 存在  2 不存在
        int isExist = jsonObject.getIntValue("isExist");

        List<String> typeList = new ArrayList<>();
        JSONArray typeMapList = jsonObject.getJSONArray("typeMapList");
        for (int i = typeMapList.size() - 1; i >= 0; i--) {
            JSONObject object = typeMapList.getJSONObject(i);
            typeList.add(object.getString("type") + "-" + object.getString("childType"));
        }

        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            for (String typChildType : typeList) {
                List<Integer> list = StringUtils.stringToIntegerList(typChildType, "-");
                if(activityInfo.getType() == list.get(0) && activityInfo.getChildType() == list.get(1)){
                    for (Long sid : serverIdList) {
                        if(activityInfo.getServerIdList().contains(sid)){
                            if(!activityServerMap.containsKey(activityInfo.getActivityId())){
                                activityServerMap.put(activityInfo.getActivityId(), new ArrayList<>());
                            }
                            activityServerMap.get(activityInfo.getActivityId()).add(sid);
                        }
                    }
                }
            }
        }

        AdminResult result = AdminResult.defaultInstance();

        List<JSONObject> existResultList = new ArrayList<>();
        List<JSONObject> noExiResultList = new ArrayList<>();

        for (String typChildType : typeList) {
            List<Integer> list = StringUtils.stringToIntegerList(typChildType, "-");
            List<ActivityInfo> activityInfoList = new ArrayList<>();
            for (Map.Entry<Integer, ActivityInfo> entry : activityInfoMap.entrySet()) {
                if(entry.getValue().getType() == list.get(0) && entry.getValue().getChildType() == list.get(1)){
                    activityInfoList.add(entry.getValue());
                }
            }
            ArrayList<Long> allServerList = new ArrayList<>(serverIdList);
            for (ActivityInfo activityInfo : activityInfoList) {
                List<Long> exitList = activityServerMap.get(activityInfo.getActivityId());
                if(exitList != null){
                    allServerList.removeAll(exitList);
                    JSONObject infoObject = new JSONObject();
                    infoObject.put("serverIds", exitList);
                    infoObject.put("activityId", activityInfo.getActivityId());
                    infoObject.put("name", activityInfo.getActivityName());
                    infoObject.put("type", activityInfo.getType());
                    infoObject.put("childType", activityInfo.getChildType());
                    infoObject.put("startShowTime", DateHelper.getCurrentDateTimeString(activityInfo.getBeginShowTime() * 1000));
                    infoObject.put("startTime", DateHelper.getCurrentDateTimeString(activityInfo.getBeginTime() * 1000));
                    infoObject.put("endTime", DateHelper.getCurrentDateTimeString(activityInfo.getEndTime() * 1000));
                    infoObject.put("endShowTime", DateHelper.getCurrentDateTimeString(activityInfo.getEndShowTime() * 1000));
                    infoObject.put("exist", 1);
                    existResultList.add(infoObject);
                }
            }
            if(!allServerList.isEmpty()){
                JSONObject infoObject = new JSONObject();
                infoObject.put("serverIds", allServerList);
                infoObject.put("activityId", 0);
                infoObject.put("name", 0);
                infoObject.put("type", list.get(0));
                infoObject.put("childType", list.get(1));
//                infoObject.put("startShowTime", DateHelper.getCurrentDateTimeString(activityInfo.getBeginShowTime() * 1000));
//                infoObject.put("startTime", DateHelper.getCurrentDateTimeString(activityInfo.getBeginTime() * 1000));
//                infoObject.put("endTime", DateHelper.getCurrentDateTimeString(activityInfo.getEndTime() * 1000));
//                infoObject.put("endShowTime", DateHelper.getCurrentDateTimeString(activityInfo.getEndShowTime() * 1000));
                infoObject.put("exist", 0);
                noExiResultList.add(infoObject);
            }
        }

        if(isExist == 0){
            existResultList.addAll(noExiResultList);
            result.getData().put("total", existResultList.size());
            result.getData().put("row", existResultList);
        }else if(isExist == 1){
            result.getData().put("total", existResultList.size());
            result.getData().put("row", existResultList);
        }else if(isExist == 2){
            result.getData().put("total", noExiResultList.size());
            result.getData().put("row", noExiResultList);
        }
        return result.toJsonString();
    }

    /**
     * 52.2 区服角色残留查询
     */
    @ResponseBody
    @RequestMapping(value = "alarm/queryServerRoleResidual", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String queryServerRoleResidual(HttpServletRequest request, @RequestBody JSONObject paramObject){

        if(!paramObject.containsKey("channelId")){
            return AdminResult.failMsg("参数不足").toJsonString();
        }
        if(!paramObject.containsKey("serverIds")){
            return AdminResult.failMsg("参数不足").toJsonString();
        }

        List<Long> serverList = new ArrayList<>();
        JSONArray array = paramObject.getJSONArray("serverIds");
        for (int i = 0; i < array.size(); i++) {
            serverList.add(Long.valueOf(array.getString(i)));
        }
        AdminResult result = new AdminResult();
        for (Long sid : serverList) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(sid);
            if(serverInfo == null){
                continue;
            }
            Map<String, String> paramMap = new HashMap<>();
            String response = HttpHelper.doPost(serverInfo.getWebServerUrl() + "/game/admin/alarm/queryServerRoleResidual", paramMap, "UTF-8");
            if(!StringUtils.isNullOrEmpty(response)){
                AdminResult serverResult = JSON.parseObject(response, AdminResult.class);
                if(serverResult != null && serverResult.getData().containsKey("num")){
                    result.getData().put(String.valueOf(sid), serverResult.getData().getIntValue("num") > 0);
                }
            }else {

            }
        }
        return result.toJsonString();
    }

    /**
     * 52.3 区服未配置活动查询
     */
    @ResponseBody
    @RequestMapping(value = "alarm/queryServerConfigActivity", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String queryServerConfigActivity(HttpServletRequest request, @RequestBody JSONObject paramObject){

        if(!paramObject.containsKey("channelId")){
            return AdminResult.failMsg("参数不足").toJsonString();
        }
        if(!paramObject.containsKey("serverIds")){
            return AdminResult.failMsg("参数不足").toJsonString();
        }

        List<Long> serverList = new ArrayList<>();
        JSONArray array = paramObject.getJSONArray("serverIds");
        for (int i = 0; i < array.size(); i++) {
            serverList.add(Long.valueOf(array.getString(i)));
        }

        AdminResult result = new AdminResult();
        long second = DateHelper.getCurrentSecond();
        for (long sid : serverList) {
            List<Integer> list = AllActivityMainInfoMgr.getActivityIdListByServerId((int) sid, second);
            result.getData().put(String.valueOf(sid), !list.isEmpty());
        }

        return result.toJsonString();
    }
}
